package com.ohy.douyin_hot;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

@SpringBootApplication
@RestController
public class DouyinHotApplication {

    public static void main(String[] args) {
        SpringApplication.run(DouyinHotApplication.class, args);
    }

    @GetMapping("douyin_hot")
    public AjaxResult test() throws IOException {
        String url = "https://www.iesdouyin.com/web/api/v2/hotsearch/billboard/aweme/";
        JSONArray jsonArray = new JSONArray(20);
        String s = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray array = jsonObject.getJSONArray("aweme_list");
        HttpURLConnection conn;
        for (int i = 0; i < array.size(); i++) {
            String desc = array.getJSONObject(i).getJSONObject("aweme_info").getString("desc");
            String vid = array.getJSONObject(i).getJSONObject("aweme_info").getJSONObject("video").getString("vid");
            String img = array.getJSONObject(i).getJSONObject("aweme_info").getJSONObject("video").getJSONObject("origin_cover").getJSONArray("url_list").getString(0);
            String uid = array.getJSONObject(i).getJSONObject("aweme_info").getJSONObject("author").getString("uid");
            url = "https://api.amemv.com/aweme/v1/play/?video_id=" + vid + "&line=1&ratio=540p&media_type=4&vr_type=0&improve_bitrate=0&is_play_url=1&is_support_h265=0&source=PackSourceEnum_PUBLISH";
            conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setConnectTimeout(5000);
            // String url2 = "https://aweme.snssdk.com/aweme/v1/play/?video_id=" + vid + "&line=0&ratio=540p&media_type=4&vr_type=0&improve_bitrate=0&is_play_url=1&is_support_h265=0&source=PackSourceEnum_PUBLISH";
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
            url = conn.getHeaderField("Location");

            JSONObject data = new JSONObject();
            data.put("desc", desc);
            data.put("img", img);
            data.put("uid", uid);
            data.put("url", url);
            jsonArray.add(data);
        }
        return AjaxResult.success(jsonArray);
    }

}
